package com.ywger.web.config.db;


import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.ywger.dao.mybatis.config.MybatisPlusObjectHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author chenmeng
 * @date 2021-07-13 13:15
 * @desc
 * mapperScan 必须需指定sqlSessionFactoryRef才能切换数据源
 * 接入mybatis plus sessionFaction需使用MybatisSqlSessionFactoryBean
 */
/*@Configuration
@MapperScan(basePackages = "com.ywger.dao.mapper.common",sqlSessionFactoryRef = "commonSqlSessionFactory")*/
public class CommonDbBeanConfig {

    @Autowired
    CommonDbDuridConfig commonDuridConfig;

    @Bean(name = "commonDbDataSource")
    public DataSource commonDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        BeanUtils.copyProperties(commonDuridConfig,dataSource);
        return dataSource;
    }

    @Bean(name = "commonDbTransactionManager")
    public DataSourceTransactionManager commonTransactionManager() {
        return new DataSourceTransactionManager(commonDataSource());
    }

    @Bean(name = "commonSqlSessionFactory")
    public SqlSessionFactory commonSqlSessionFactory(@Qualifier("commonDbDataSource") DataSource commonDataSource)
            throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean ();
        GlobalConfig globalConfig = GlobalConfigUtils.defaults();
        globalConfig.setMetaObjectHandler(new MybatisPlusObjectHandler());
        sessionFactory.setGlobalConfig(globalConfig);
        sessionFactory.setDataSource(commonDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(commonDuridConfig.getMybatisMapperLocation()));

        return sessionFactory.getObject();
    }
}
